<script setup>
import { ref } from 'vue';
import { Panel, VueFlow, useVueFlow } from '@vue-flow/core';
import CustomNode from './components/CustomNode.vue';

const instance = useVueFlow();
const { onConnect, addEdges, vueFlowRef, onEdgeUpdateEnd, applyEdgeChanges, fitView, applyNodeChanges } = instance;
onConnect(addEdges);

const nodes = ref([
  {
    id: '1',
    position: { x: 50, y: 50 },
    type: 'custom',
    data: { label: 'Node 1' },
  },
  {
    id: '2',
    position: { x: 80, y: 90 },
    type: 'custom',
    data: { label: 'Node 2' },
  },
]);

const edges = ref([{ id: 'e1-2', source: '1', target: '2', type: 'default' }]);

const { addNodes } = useVueFlow();

function onAddNode() {
  // add a single node to the graph
  addNodes({
    id: Math.random().toString(),
    type: 'custom',
    position: { x: Math.random() * 500, y: Math.random() * 500 },
    label: 'Random Node',
  });
}

// =========== 返回相关

// 数组中存的是对象
const nodesAndEdgesStore = ref([]);
let currentNodesChange = null;
let currentEdgesChange = null;
const rebackNodes = () => {
  let p = nodesAndEdgesStore.value.shift();
  console.log('rebackNodes 开始返回', p, instance);
  if (p) {
    nodes.value = p.nodes;
    edges.value = p.edges;
    // instance.fitView();
  }
};

// 一个五秒的防抖函数
const throttle = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

const toStoreNodesAndEdges = throttle(() => {
  console.log('storeNodesAndEdges 存入了节点和边');
  storeNE();
}, 2000);

const storeNE = () => {
  let param = {
    nodes: JSON.parse(JSON.stringify(nodes.value)),
    edges: JSON.parse(JSON.stringify(edges.value)),
  };
  nodesAndEdgesStore.value.unshift(param);

  //   存入之后再去改变
  if (currentNodesChange) {
    applyNodeChanges(currentNodesChange);
    currentNodesChange = null;
  }
  if (currentEdgesChange) {
    applyEdgeChanges(currentEdgesChange);
    currentEdgesChange = null;
  }
};

const onNodesChange = (changes) => {
  console.log('N--C');
  currentNodesChange = changes;
  toStoreNodesAndEdges();
};

const onEdgesChange = (changes) => {
  console.log('E--C');
  currentNodesChange = changes;
  toStoreNodesAndEdges();
};

const flowRef = ref(null);
</script>

<template>
  <VueFlow
    ref="flowRef"
    v-model:nodes="nodes"
    v-model:edges="edges"
    :apply-default="false"
    @nodes-change="onNodesChange"
    @edges-change="onEdgesChange"
  >
    <template #node-custom="customNodeProps">
      <CustomNode v-bind="customNodeProps" />
    </template>
    <Panel>
      <button type="button" @click="rebackNodes">返回</button>
      <button type="button" @click="onAddNode">Add a node</button>
    </Panel>
  </VueFlow>
</template>
